'use strict';

import config from './index';
import morgan from 'koa-morgan';
import parser from 'koa-bodyparser';
import compress from 'koa-compress';
import views from 'koa-views';
import fileServer from '../middleWare/fileSever';
import cors from 'koa2-cors';

export default function configKoa(app) {
  app.use(compress());
  app.use(cors({
    origin: (ctx) => {
      // console.log(ctx.url.indexOf('/api'));
      if (ctx.url.indexOf('/api') === -1) {
        return false;
      }
      return '*';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  }));
  app.use(parser({
    strict: false
  }));
  app.use(views(config.webRoot));
  app.use((ctx, next) => {
    console.log('filemiddle', ctx.request.url.split('/')[1]);
    if (ctx.request.url.split('/')[1] === 'static') {
      app.use(fileServer());
      return next();
    } else {
      return next();
    }
  });
  // app.use(fileServer());
  app.use((ctx, next) => {
    ctx.body = ctx.request.body;
    return next();
  });
  app.on('error', err => console.error(err));
  app.use(morgan(config.logType));
}
